package com.moody.init;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.moody.hibernate.dao.OrgInfoDAO;
import com.moody.hibernate.dao.ReportModelDAO;
import com.moody.hibernate.domain.OrgInfo;

public class OrgInit {
	private static final Logger log = LoggerFactory
			.getLogger(OrgInit.class);
	private static OrgInit instance = null;
	static WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
	static ServletContext context = web.getServletContext();  
	static WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context);
	private static OrgInfoDAO orgInfoDAO = OrgInfoDAO.getFromApplicationContext(ctx);
	private static Map<String,List<String>> orgMap = new HashMap<String,List<String>>();
	
	private OrgInit() {
	}
	
	public static OrgInit getInstance(){
		if(instance == null){
			instance = new OrgInit();
		}
		return instance;
	}
	
	public Map<String,List<String>> getOrgInfoMap(){
		List<OrgInfo> orgList = orgInfoDAO.findAll();
		
		if(orgMap==null || orgMap.size()==0){
			for(OrgInfo orgInfo : orgList){
				
				List<String> subOrgList = new ArrayList<String>();
				//如果是总部
				if(orgInfo.getOrgCode().equals("0")){
					for(OrgInfo org : orgList){
						if(!org.getOrgCode().equals("0")){
							subOrgList.add(org.getOrgId());
						}
					}
				}
				//非总部
				else{
					List<OrgInfo> subList = orgInfoDAO.findByOrgCode(orgInfo.getOrgId());
					for(OrgInfo org : subList){
						subOrgList.add(org.getOrgId());
					}
				}
				
				//不将自己加入。因为我们使用这个map逻辑是：如果这个客户的inputUserId==logonUser或者客户的inputOrgId包含在user所管辖的子机构中，才可以被显示。
				//subOrgList.add(orgInfo.getOrgId());
				orgMap.put(orgInfo.getOrgId(), subOrgList);
			}
			log.info("orgMap: "+orgMap);
			return orgMap;
		}else{
			log.info("orgMap: "+orgMap);
			return orgMap;
		}
	}
	
}
